﻿
using TouchSocket.Core;
using TouchSocket.Modbus;
using TouchSocket.SerialPorts;
using TouchSocket.Sockets;

var slaveQty = 80;

try
{
    Enterprise.ForTest();

}
catch (System.Exception)
{
}

TouchSocketBitConverter.DefaultEndianType = EndianType.Big;
var slave = new ModbusRtuSlave();
await slave.SetupAsync(new TouchSocketConfig()
     //设置串口
     .SetSerialPortOption(new SerialPortOption()
     {
         BaudRate = 9600,
         DataBits = 8,
         Parity = System.IO.Ports.Parity.Even,
         PortName = "COM1",
         StopBits = System.IO.Ports.StopBits.One
     })
     .ConfigurePlugins(a =>
     {

         for (int i = 0; i < slaveQty; i++)
         {
             a.AddModbusSlavePoint()//添加一个从站站点
                .SetSlaveId((byte)(i + 1))//设置站点号
                .SetModbusDataLocater(new ModbusDataLocater(10, 10, 10, 10));//设置数据区
         }
     })
     );

await slave.ConnectAsync();
Console.WriteLine("已连接COM端口");

while (true)
{

    var random = new Random();

    for (int i = 0; i < slaveQty; i++)
    {
        var modbusSlavePoint = slave.GetSlavePointBySlaveId(slaveId: (byte)(i + 1));
        var localMaster = modbusSlavePoint.ModbusDataLocater.CreateDataLocaterMaster();
        localMaster.WriteSingleRegister((byte)(i + 1), 7, (ushort)(2732 + random.Next(1, 30)*10), 500, default);

        localMaster.WriteSingleRegister(6, (short)random.Next(1, short.MaxValue));
    }
    await Task.Delay(10);
}

Console.Read();